package com.yearner.reviewplan.manage.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yearner.reviewplan.manage.system.bean.MenuVo;
import com.yearner.reviewplan.manage.system.dao.UserPermDao;
import com.yearner.reviewplan.manage.system.entity.UserPerm;
import com.yearner.reviewplan.manage.system.service.UserPermService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 权限表 服务实现类
 *
 * @author Pengyg
 * @since 2020-01-10
 */
@Service("UserPermService")
public class UserPermServiceImpl extends ServiceImpl<UserPermDao, UserPerm> implements UserPermService {


    @Override
    public List<MenuVo> getMenus() {
        List<UserPerm> list = baseMapper.selectRootMenu();
        List<MenuVo> menuVos = new ArrayList<>();
        for (UserPerm perm : list) {
            menuVos.add(traversePerm(perm));
        }
        return menuVos;
    }

    @Override
    public MenuVo getMenuInList(List<MenuVo> list, Integer id) {
        MenuVo menu = null;
        for (MenuVo a : list) {
            if (a.getMenuId().equals(id)) {
                menu = a;
                break;
            }
            if (a.getChildren() != null && a.getChildren().size() > 0) {
                Optional<MenuVo> maybe = Optional.ofNullable(getMenuInList(a.getChildren(), id));
                if (maybe.isPresent()) {
                    menu = maybe.get();
                    break;
                }
            }
        }
        return menu;
    }

    @Override
    public void deleteById(List<Integer> ids) {
        List<UserPerm> willDelete = listByIds(ids);
        List<UserPerm> updateChild = new ArrayList<>();
        // 如果它有子节点，则将子节点改为它的父节点
        for (UserPerm dd : willDelete) {
            MenuVo menuVo = traversePerm(dd);
            if (menuVo.getChildren() != null) {
                for (MenuVo child : menuVo.getChildren()) {
                    // 如果在删除列表中，就不做处理
                    if (ids.contains(child.getMenuId())) {
                        continue;
                    }
                    child.setParentId(dd.getParentId());
                    updateChild.add(child.getUserPerm());
                }
            }
        }
        removeByIds(ids);
        if (!updateChild.isEmpty()) {
            updateBatchById(updateChild);
        }
    }


    private MenuVo traversePerm(UserPerm perm) {
        // 新建一个菜单
        MenuVo aside = new MenuVo(perm);

        List<UserPerm> childrenPerm = baseMapper.getChildren(perm.getPermId());
        List<MenuVo> childrenAside = new ArrayList<>();
        // 拥有子菜单
        for (UserPerm userPerm : childrenPerm) {

            aside.setChildren(childrenAside);

            MenuVo child = traversePerm(userPerm);
            child.setParentName(aside.getTitle());
            childrenAside.add(child);
        }

        return aside;
    }
}
